package tech.lingrui.mnpanonymousservice.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.util.JSONPObject;
import lombok.extern.slf4j.Slf4j;
import tech.lingrui.mnpanonymousservice.model.bean.GameModel;
import tech.lingrui.mnpanonymousservice.model.bean.Round;
import tech.lingrui.mnpanonymousservice.model.bean.UserModel;
import tech.lingrui.mnpanonymousservice.model.message.BaseMessage;
import tech.lingrui.mnpanonymousservice.model.message.GameResultMessage;
import tech.lingrui.mnpanonymousservice.model.message.ResponseMessage;
import tech.lingrui.mnpanonymousservice.service.RoundService;
import tech.lingrui.mnpanonymousservice.util.JsonUtils;
import tech.lingrui.mnpanonymousservice.websocket.GameWebSocket;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class RoundServiceImpl implements RoundService {

    private GameModel gameModel;
    private Map<UserModel, GameWebSocket> clients;
    private Map<Integer, Round> rounds;

    /**
     * 已经进行完成的回合数量
     * */
    private int alreadyAnsweredNum = 0;

    /**
     * 上一题是谁回答的
     * */
    private UserModel prevAnswered;

    /**
     * 现在进行的回合
     * */
    private Round currentRound;

    public  RoundServiceImpl(GameModel gameModel){
        this.gameModel = gameModel;
        this.clients = GameWebSocket.getClients();
        this.rounds = gameModel.getRounds();
    }

    @Override
    public void startFirstRound()  {
        //默认给创建者发第一道题
        UserModel creator = gameModel.getCreator();
        UserModel participant = gameModel.getParticipant();

        currentRound  = rounds.get(1);
        currentRound.setOwner(creator);

        ResponseMessage msg = new ResponseMessage();
        msg.setData(currentRound);
        msg.setType(BaseMessage.MSY_TYPE_ROUND);

        try {
            this.clients.get(creator).sendMessageToUser(creator.getName(), msg);
            this.clients.get(participant).sendMessageToUser(participant.getName(),msg);
        } catch (IOException e) {
            log.info("");
        }


        //执行下一回合
        alreadyAnsweredNum++;
        prevAnswered = creator;
    }

    @Override
    public void goNextRound(Round preRound) {
        if(alreadyAnsweredNum<this.rounds.size()){

            currentRound = rounds.get(alreadyAnsweredNum+1);
            currentRound.setPrevRoundAnswer(preRound.getQuestion().getRightNo());
            currentRound.setPrevRoundHisAnswer(preRound.getAnswerNo());

            //构建消息
            ResponseMessage msg = new ResponseMessage();
            msg.setData(currentRound);
            msg.setType(BaseMessage.MSY_TYPE_ROUND);

            //判断上一题是谁答得
            if(prevAnswered==gameModel.getCreator()){
                try {
                    //发题目
                    currentRound.setOwner(gameModel.getParticipant());
                    this.clients.get(gameModel.getParticipant()).sendMessageToUser(gameModel.getParticipant().getName(), msg);
                    this.clients.get(gameModel.getCreator()).sendMessageToUser(gameModel.getCreator().getName(), msg);
                } catch (IOException e) {
                    log.info("");
                }
                prevAnswered = gameModel.getParticipant();
            }else if(prevAnswered==gameModel.getParticipant()){
                try {
                    currentRound.setOwner(gameModel.getCreator());
                    this.clients.get(gameModel.getCreator()).sendMessageToUser(gameModel.getCreator().getName(), msg);
                    this.clients.get(gameModel.getParticipant()).sendMessageToUser(gameModel.getParticipant().getName(), msg);
                } catch (IOException e) {
                    log.info("");
                }
                prevAnswered = gameModel.getCreator();
            }
        }
    }
    @Override
    public void handleAnswer(int answer) {

        currentRound.setAnswerNo(answer);
        //检查答案
        int correctAnswer = currentRound.getQuestion().getRightNo();
        if(answer==correctAnswer){
            currentRound.setAnswerRight(true);
        }else{
            currentRound.setAnswerRight(false);
        }
        alreadyAnsweredNum++;

        goNextRound(currentRound);


        if(alreadyAnsweredNum==this.rounds.size()){
            try {
                backLastOneResult(answer);
                finishRounds();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 由于每次返回题目都会返回前一题的结果，所以最后一题
     * 无法给出结果，此方法用于返回最后一题的结果
     * */

    public void backLastOneResult(int lastHisAnswer){
        try {

            Map<String,Integer> result= new HashMap<>();
            result.put("prevRoundAnswer",currentRound.getQuestion().getRightNo());
            result.put("prevRoundHisAnswer",lastHisAnswer);

            ResponseMessage msg = new ResponseMessage();
            msg.setData(result);
            msg.setType(BaseMessage.MSY_TYPE_ROUND);

            this.clients.get(gameModel.getParticipant()).sendMessageToUser(gameModel.getParticipant().getName(), msg);
            this.clients.get(gameModel.getCreator()).sendMessageToUser(gameModel.getCreator().getName(), msg);
        } catch (IOException e) {
            log.info("");
        }
    }


    @Override
    public void finishRounds() throws IOException {
        //统计结果
        GameResultMessage message = new GameResultMessage();
        message.setAllQueNum(this.rounds.size());


        int creatorCorrectNum = 0;
        int participantCorrectNum = 0;
        for(Round round:rounds.values()){
            if(round.getOwner()==gameModel.getCreator()){
                if(round.isAnswerRight()){
                    creatorCorrectNum++;
                }
            }
            if(round.getOwner()==gameModel.getParticipant()){
                if(round.isAnswerRight()){
                    participantCorrectNum++;
                }
            }

        }

        if(creatorCorrectNum>participantCorrectNum){
            message.setWinner(gameModel.getCreator());
            message.setLoser(gameModel.getParticipant());
            message.setLoserCorrectNum(participantCorrectNum);
            message.setWinnerCorrectNum(creatorCorrectNum);
        }else{
            message.setWinner(gameModel.getParticipant());
            message.setLoser(gameModel.getCreator());
            message.setLoserCorrectNum(creatorCorrectNum);
            message.setWinnerCorrectNum(participantCorrectNum);
        }
        message.setWinnerGetIntegral(gameModel.getWinnerIntegral());
        message.setLoserLostIntegral(gameModel.getLoserIntegral());

        ResponseMessage msg = new ResponseMessage();
        msg.setType(ResponseMessage.MSY_TYPE_GAME_OVER);
        msg.setData(message);

        clients.get(gameModel.getCreator()).sendMessageToUser(gameModel.getCreator().getName(),msg);
        clients.get(gameModel.getParticipant()).sendMessageToUser(gameModel.getParticipant().getName(),msg);
    }
}
